const fs = require('fs');
const path = require('path');

// 工具方法
const Utils = {
    createFolder(dirPath, dirName){
        if (typeof dirName === "undefined") {
            if (fs.existsSync(dirPath)) {
            } else {
                Utils.createFolder(dirPath, path.dirname(dirPath));
            }
        } else {
            if (dirName !== path.dirname(dirPath)) {
                Utils.createFolder(dirPath);
                return;
            }
            if (fs.existsSync(dirName)) {
                fs.mkdirSync(dirPath)
            } else {
                Utils.createFolder(dirName, path.dirname(dirName));
                fs.mkdirSync(dirPath);
            }
        }
    },

    /**
     * 复制文件
     * @param {String} orgfilepath 原始的文件路径
     * @param {String} desdirpath 新的文件夹地址
     * @param {String} desfilename 新的文件名称
     */
    copyFile(orgfilepath, desdirpath, desfilename) {
        if (fs.existsSync(orgfilepath)) {
            let desfilepath = path.join(desdirpath, desfilename);
            if (!fs.existsSync(desfilepath)) {
                Utils.createFolder(desdirpath);
                fs.copyFileSync(orgfilepath, desfilepath);
            } else {
                console.error(Date().toString() + "FolderAndFileOperation_copyFile: des file already existed." + " new path: " + desfilepath.toString());
            }
        } else {
            console.error(Date().toString() + "FolderAndFileOperation_copyFile: org file not existed." + " org path: " + orgfilepath.toString());
        }
    },

    /**
     * 获取文件后缀
     * @param filename
     * @return {*}
     */
    getFileSuffix(filename) {
        return filename.slice(filename.lastIndexOf('.'), filename.length)
    }
}

// 接口响应内容包装
const Result = {
    ok: (data = null, message = null) =>
        JSON.stringify({code: 200, data, message}),
    fail: (message, data = null) =>
        JSON.stringify({code: 500, data, message}),
};

module.exports = {
    Utils,
    Result
}
